package com.magnusart.scrumify.dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.magnusart.scrumppm.model.Project;
import com.magnusart.scrumppm.model.ProjectBuilder;

public class HsqlDbProjectDAO extends HsqlDbAbstactDAO<Project, Project, ProjectBuilder>
{

	public HsqlDbProjectDAO( HsqlDbDAOFactory factory ) {
		super( factory );
	}
	
	{		
		sqlAdd = "INSERT INTO Projects( projectName, " +
		"description, isDone ) " +
		"VALUES( ?, ?, ? )";
		
		sqlGetAll = "SELECT projectName, " +
		" description, " +
		"isDone " +
		"FROM Projects";
		
		sqlGetOne = "SELECT projectName, " +
		"description, " +
		"isDone " +
		"FROM Projects WHERE projectName = ?";
		
		sqlUpdate = "UPDATE Projects SET " +
		"projectName = ?, " +
		"description = ?, " +
		"isDone = ? " +
		"WHERE projectName = ? ";
		
		sqlDelete = "DELETE FROM Projects WHERE projectName = ?";
	}
	

	@Override
	Project pepareUpdate( Project parent, Project entry,
			ProjectBuilder builder, PreparedStatement pstmt)
			throws SQLException {
		// Project is immutable, ProjectBuilder is not.
		Project updated = new Project( builder );
		
		pstmt.setString( 1, updated.getName() );
		pstmt.setString( 2, updated.getDescription() );
		pstmt.setBoolean( 3, updated.isDone() );
		pstmt.setString( 4, entry.getName() );
		
		return updated;
	}

	@Override
	void perpareAdd( Project parent, Project entry, PreparedStatement pstmt)
			throws SQLException {
		pstmt.setString( 1, entry.getName() );
		pstmt.setString( 2, entry.getDescription() );
		pstmt.setBoolean( 3, entry.isDone() );
		
	}
	

	@Override
	void prepareDelete( Project entry, PreparedStatement pstmt)
			throws SQLException {
		pstmt.setString( 1, entry.getName() );
	}

	@Override
	void prepareGetAll( Project parent, PreparedStatement pstmt)
			throws SQLException {
		/* Nothing */
	}

	@Override
	void prepareGetOne( Project entry, PreparedStatement pstmt)
			throws SQLException {
		pstmt.setString( 1, entry.getName() );
	}
	
	@Override
	Project addedEntry( DAOFactory factory, Project entry, ProjectBuilder builder, int addedID) {
		return entry;
	}

	@Override
	Project fetchBuilderData( ResultSet rs, ProjectBuilder builder)
			throws SQLException {
		builder = new ProjectBuilder();
		builder.setName( rs.getString( "projectName" ) );
		builder.setDescription( rs.getString( "description" ) );
		builder.setDone( rs.getBoolean( "isDone" ) );
		return new Project( builder );
	}
}
